#!/bin/bash

obs_project="home:maminjie:branches:openEuler:function"
obs_repo='standard_aarch64'
obs_arch='aarch64'
yum_repo='/etc/yum.repos.d/abcded.repo'
result_file='result.txt'
project_file='project.txt'
find_prj_enable=no

usage() {
    echo "Usage:"
    echo "    script [OPTS] [ARGS...]"
    echo ""
    echo "Options:"
    echo "    -p PROJECT"
    echo "              analyse the specified obs project"
    echo "    -r REPO"
    echo "              analyse the specified obs repository"
    echo "    -a ARCH"
    echo "              analyse the specified obs arch"
    echo "    -h"
    echo "              show the help information"
    echo "    -f"
    echo "              find the obs project for rely packages"
    echo ""
}

while getopts "p:r:a:fh" opt; do
    case $opt in
        p)
            obs_project=$OPTARG
            ;;
        r)
            obs_repo=$OPTARG
            ;;
        a)
            obs_arch=$OPTARG
            ;;
        f)
            find_prj_enable=yes
            ;;
        *)
            usage
            exit
            ;;
    esac
done

add_yumrepo() {
printf "\
[$1]
name=$1
baseurl=$2
enabled=1
gpgcheck=0
\n" >> $yum_repo
}

config_yumrepos() {
    local urlprefix=http://mirrors.aliyun.com/fedora
    local osversion=30

    add_yumrepo repo-r $urlprefix/releases/$osversion/Everything/aarch64/os
    add_yumrepo repo-r-src $urlprefix/releases/$osversion/Everything/source/tree
    add_yumrepo repo-u $urlprefix/updates/$osversion/Everything/aarch64
    add_yumrepo repo-u-src $urlprefix/updates/$osversion/Everything/SRPMS
}

remove_yumrepos() {
    rm -rf $yum_repo
}

analyse() {
    local unresolved_pkgs=$(osc pr $obs_project -s U -r $obs_repo -a $obs_arch -q -V | sed 1d | sed '$d' | sed '$d' | awk '{print $2}')

    # do query
    printf "%s\t%s\t%s\t%s\n" PKG DEP BIN SRC
    for x in $unresolved_pkgs; do
        relys=$(osc r $obs_project $x -r $obs_repo -a $obs_arch -v | grep -v unresolv | awk '{print $3}')
        for y in $relys; do
            bin=`dnf repoquery --whatprovides "$y" --repo repo-r --repo repo-u -q | head -n1 | sed 's/-[[:digit:]]\+.*//'`
            src=`dnf repoquery -q -i $bin --repo repo-r --repo repo-u | grep Source | head -n1 | awk '{print $3}' | sed 's/-[[:digit:]]\+.*//'`
            printf "%s\t%s\t%s\t%s\n" $x $y $bin $src
        done
    done | tee $result_file
}

find_project() {
    local rely_pkgs=$(cat $result_file | awk '{print $4}' | sort | uniq)
    
    printf "%s\t%s\n" PKG PRJ
    for x in $rely_pkgs; do
        local prjs=$(osc search --package "$x" | awk '{print $1}' | tail -n +4)
        for y in $prjs; do
            printf "%s\t%s\n" $x $y
        done
    done | tee $project_file
}

main() {
    config_yumrepos
    analyse
    remove_yumrepos

    if [ "$find_prj_enable" = "yes" ]; then
        find_project
    fi

    echo "============================="
    echo "PLEASE check the $result_file"
    echo "============================="
}

main "$@"

